<?php

declare(strict_types=1);

namespace app\model;

use think\Model;

/**
 * @mixin \think\Model
 */
class UserFriend extends Model
{
  //

  public function friend()
  {
    return $this->belongsTo(User::class,'friend_id');
  }

  public function user()
  {
    return $this->belongsTo(User::class,'user_id');
  }

  public static function quickOptions($user_id, $friend_id)
  {
    if (self::isFriend($user_id, $friend_id)) {
      return self::breakFriend($user_id, $friend_id);
    } else {
      return self::withFriend($user_id, $friend_id, true);
    }
  }

  public static function withFriend($user_id, $friend_id, $is_force = false)
  {
    if (!$is_force) {
      if (self::isFriend($user_id, $friend_id)) {
        return true;
      }
    }

    UserFriend::create([
      'user_id' => $user_id,
      'friend_id' => $friend_id
    ]);

    return true;
  }

  public static function breakFriend($user_id, $friend_id)
  {
    UserFriend::where('user_id', $user_id)
      ->where('friend_id', $friend_id)
      ->delete();

    return true;
  }

  public static function isFriend($user_id, $friend_id)
  {

    $model_friend = UserFriend::where('user_id', $user_id)
      ->where('friend_id', $friend_id)
      ->find();

    if (empty($model_friend)) {
      return false;
    }

    return true;
  }
}
